import pandas as pd
from mlxtend.preprocessing import TransactionEncoder
from mlxtend.frequent_patterns import apriori, association_rules
import matplotlib.pyplot as plt
import networkx as nx

# 修改为正确的文件路径
file_path = 'C:\\Users\\Administrator\\Desktop\\餐厅数据.xlsx'

df = pd.read_excel(file_path)

# 转换菜品数据格式
transactions = df['菜品'].str.split(',').to_list()

# 标准化数据 
te = TransactionEncoder()
te_ary = te.fit(transactions).transform(transactions)
df_encoded = pd.DataFrame(te_ary, columns=te.columns_)

# 使用apriori进行关联规则挖掘
frequent_itemsets = apriori(df_encoded, min_support=0.1, use_colnames=True)
frequent_itemsets.sort_values(by='support', ascending=False, inplace=True)

# 生成关联规则
rules = association_rules(frequent_itemsets, metric='confidence', min_threshold=0.1)

# 筛选有效规则
effective = rules[
    (rules['lift'] > 1) & (rules['confidence'] > 0.1)
].sort_values(by=['lift', 'confidence'], ascending=False)

# 输出结果
print(effective[['antecedents', 'consequents', 'support', 'confidence', 'lift']])